package com.pan.lianjia;

import com.pan.crawler.HouseCrawler;
import com.pan.crawler.entity.HouseInfo;
import com.pan.utils.Sleep;
import com.pan.utils.WriteFileCSV;

import java.util.HashMap;
import java.util.List;

public class LianJiaCrawlerDriver {

    private HouseCrawler houseCrawler;
    private HashMap<String,String> itemMap = new HashMap<>();
    public LianJiaCrawlerDriver(){

    }{
        itemMap.put("1","天河");
        itemMap.put("2","越秀");
        itemMap.put("3","荔湾");
        itemMap.put("4","海珠");
        itemMap.put("5","番禺");
        itemMap.put("6","白云");
        itemMap.put("7","黄埔");
        itemMap.put("8","从化");
        itemMap.put("9","增城");
        itemMap.put("10","花都");
        itemMap.put("11","南沙");
    }

    public void run(){
        houseCrawler = new LianJiaCrawlerImpl("https://gz.lianjia.com/zufang/baiyun/rt200600000001/");
        String itemFile = "";
        WriteFileCSV gCsv = null;
        WriteFileCSV zCsv = null;
        while (houseCrawler.hasNxtItem()){
            String item = houseCrawler.nextItem();
            item = itemMap.get(item);
            //delete
            if (!item.equals("白云"))break;
            //delete
            if (!item.equals(itemFile)){
                itemFile = item;
                if (gCsv!=null){
                    gCsv.close();
                }if (zCsv!= null){
                    zCsv.close();
                }
                gCsv = new WriteFileCSV(itemFile+"_公寓");
                zCsv = new WriteFileCSV(itemFile+"_房东");
            }
            while (houseCrawler.hasNxtPage()){
                Sleep.sleep();
                String pageUrl = houseCrawler.nextPage();
                System.out.println("开始爬取："+ pageUrl);
                HashMap<Integer, List<HouseInfo>> pageHouseMap = houseCrawler.getPageHouse();
                List<HouseInfo> zInfo = pageHouseMap.get(LianJiaCrawlerImpl.HouseType.No_Apartment.getType());
                List<HouseInfo> gInfo = pageHouseMap.get(LianJiaCrawlerImpl.HouseType.Apartment.getType());
                if (zInfo.size()!= 0 ){
                    zCsv.appendData(zInfo);
                }
                if (gInfo.size() != 0){
                    gCsv.appendData(gInfo);
                }
            }
        }
        if (gCsv!=null){
            gCsv.close();
        }if (zCsv!= null){
            zCsv.close();
        }
    }

}
